<template>
  <el-card shadow="never">
    <!-- 头面包屑区域 -->
    <div slot="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 筛选区域 -->
    <div class="filter-bar">
      <!-- 搜素区域 -->
      <div class="l-form"></div>
      <!-- 添加区域 -->
      <div class="r-btn">
        <el-button type="primary" size="small" @click="addRoleShow = true">增加</el-button>
      </div>
    </div>
    <!-- 表格区域 -->
    <div class="table-box">
      <el-table :data="rolelist" border>
        <el-table-column type="expand">
          <!-- 这里放折叠的信息 -->
          <template slot-scope="scope">
            <el-row class="line-row" v-for="item in scope.row.children" :key="item.id">
              <el-col :span="7">
                <el-tag type="success" class="el-icon-caret-right">
                  {{
                  item.authName
                  }}
                </el-tag>
              </el-col>
              <el-col :span="17">
                <el-row class="line-row" v-for="val in item.children" :key="val.id">
                  <el-col :span="8">
                    <el-tag>{{ val.authName }}</el-tag>
                  </el-col>
                  <el-col :span="16">
                    <el-tag
                      type="warning"
                      closable
                      v-for="value in val.children"
                      :key="value.id"
                      @close="delSingRight(scope.row, value.id)"
                    >{{ value.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" align="center"></el-table-column>
        <el-table-column label="角色名称" align="center" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" align="center" prop="roleName"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="small" icon="el-icon-edit" circle></el-button>
            <el-button
              type="warning"
              size="small"
              icon="el-icon-setting"
              @click="roleAuthSet(scope.row)"
              circle
            ></el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="delRoleAuth(scope.row.id)"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 角色授权弹窗 -->
    <el-dialog title="角色授权" :visible.sync="roleShow" width="30%" @close="defCheck = []">
      <!-- 树形控件 -->
      <el-tree
        v-if="roleShow"
        ref="tree"
        :data="rightlist"
        :props="{ label: 'authName', children: 'children' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="defCheck"
      ></el-tree>

      <span slot="footer">
        <el-button @click="roleShow = false">取消</el-button>
        <el-button @click="roleAuthSubmit" type="primary">确定</el-button>
      </span>
    </el-dialog>
    <!-- 增加角色弹窗 -->
    <el-dialog title="增加角色" :visible.sync="addRoleShow" width="40%" @close="closeDia">
      <el-form
        :model="roleForm"
        ref="roleForm"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="addRoleShow = false">取消</el-button>
        <el-button type="primary" @click="addRoleSubmit">提交</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { mapActions, mapState } from "vuex";
export default {
  data() {
    return {
      roleShow: false, // 授权弹框开关
      addRoleShow: false, // 添加弹框开关
      defCheck: [],
      roleId: null,
      // 添加角色表单数据
      roleForm: {
        roleName: "",
        roleDesc: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      rightlist: (state) => state.right.rightlist,
      rolelist: (state) => state.role.rolelist,
    }),
  },
  //   调用方法获取数据
  created() {
    !this.rightlist.length && this.get_right_list();
    !this.rolelist.length && this.get_role_list();
  },
  methods: {
    ...mapActions({
      get_right_list: "right/get_right_list",
      get_role_list: "role/get_role_list",
    }),

    // 删除权限
    async delSingRight(row, rightId) {
      //   console.log(roleId, rightId);
      try {
        await this.$confirm("确定删除吗,?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // 发送请求
        let { data: res } = await this.$axios.delete(
          "roles/" + row.id + "/rights/" + rightId
        );
        // 错误处理
        if (res.meta.status != 200) return this.$message.error(res.meta.msg);
        // 成功处理;
        this.$message.success("删除成功");
        // row表示这一行的数据信息,row.children是用户的所有权限,
        // 删除后返回的用户现在所有权限
        row.children = res.data;
        // 取消提示用户
      } catch (error) {
        this.$message.info("取消删除");
      }
    },
    roleAuthSet(row) {
      this.roleShow = true;
      this.roleId = row.id;
      this.getLeafKeys(row, this.defCheck);
    },
    getLeafKeys(node, arr) {
      //该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      //如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id);
      }
      //递归调用
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    async roleAuthSubmit() {
      let authlist = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys(),
      ];

      //发送请求完成更新
      const { data: res } = await this.$axios.post(
        `roles/${this.roleId}/rights`,
        {
          rids: authlist.join(","),
        }
      );
      if (res.meta.status !== 200) return this.$message.error("分配权限失败");
      this.$message.success("分配权限成功");
      this.getrolelist();
      //关闭对话框
      this.roleShow = false;
    },
    async delRoleAuth(id) {
      try {
        await this.$confirm("确定删除吗,?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // 发送请求
        let { data: res } = await this.$axios.delete("roles/" + id);
        // 错误处理
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        // 成功处理;
        this.$message.success("删除成功");
        // row表示这一行的数据信息,row.children是用户的所有权限,
        this.getrolelist();
      } catch (error) {
        this.$message.info("取消删除");
      }
    },
    async addRoleSubmit() {
      // 查看验证结果
      this.$refs.roleForm.validate((valid) => {
        if (!valid) return this.$message.error("提交失败");
      });
      // 提交数据;
      let { data: res } = await this.$axios.post("roles", this.roleForm);
      // 错误处理
      console.log(res.meta.status);
      if (res.meta.status != 201) return this.$message.error(res.meta.msg);
      // 成功处理
      this.$message.success(res.meta.msg);
      // 重新拉去数据
      this.getrolelist();
      // 关闭弹窗;
      this.addRoleShow = false;
    },
    // 弹窗关闭时清除表单事件
    closeDia() {
      // console.log(11);
      this.$refs.roleForm.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
.line-row {
  border-bottom: 1px solid #eee;
  .el-tag {
    margin: 10px;
  }
}
.line-row:last-child {
  border: none;
}
</style>